package qs.openxt.libs.util;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

/**
 * 根据资源的名字获取其ID值
 * 
 * @author zhaoyingjie
 * 
 */
public class MResource {

	public static int getIdByName(Context context, String className, String name) {
		String packageName = context.getPackageName();
		Class r = null;
		int id = 0;
		try {
			r = Class.forName(packageName + ".R");

			Class[] classes = r.getClasses();
			Class desireClass = null;

			for (int i = 0; i < classes.length; ++i) {
				if (classes[i].getName().split("\\$")[1].equals(className)) {
					desireClass = classes[i];
					break;
				}
			}

			if (desireClass != null)
				id = desireClass.getField(name).getInt(desireClass);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return id;
	}

	public static int getDrawableByName(Context context, String name) {
		String packageName = context.getPackageName();
		Class r = null;
		int id = 0;
		try {
			r = Class.forName(packageName + ".R");

			Class[] classes = r.getClasses();
			Class desireClass = null;
			String className = "mipmap";
			for (int i = 0; i < classes.length; ++i) {
				if (classes[i].getName().split("\\$")[1].equals(className)) {
					desireClass = classes[i];
					break;
				}
			}
			if(desireClass == null){
				className = "drawable";
				for (int i = 0; i < classes.length; ++i) {
					if (classes[i].getName().split("\\$")[1].equals(className)) {
						desireClass = classes[i];
						break;
					}
				}
			}

			if (desireClass != null)
				id = desireClass.getField(name).getInt(desireClass);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return id;
	}

	/**
	 * 获得系统版本号
	 *
	 * @return 系统版本号
	 */
	public static String getVersion(Context context) {
		String version = "";
		PackageManager packageManager = context.getPackageManager();
		try {
			PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), PackageManager.GET_CONFIGURATIONS);
			version = packInfo.versionName;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return version;
	}
}